package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrEnum;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;

public class ProxySet extends AxdrType {
    private ByteBuffer dataCode = null;
    private OAD oad = null;
    private AxdrEnum dar = null;

    public ProxySet() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = ByteBuffer.wrap(dataCode);
    }

    public void setAll(OAD oad, AxdrEnum dar) {
        this.oad = oad;
        this.dar = dar;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.oad = new OAD();
        codeLength += this.oad.decode(input);
        this.dar = new AxdrEnum();
        this.dar.setConst();
        codeLength += this.dar.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.array().length;
            for (int i = this.dataCode.array().length - 1; i >= 0; i--) {
                output.write(this.dataCode.array()[i]);
            }
        } else {
            if (this.dar != null && this.oad != null) {
                codeLength = 0;
                codeLength += this.dar.encode(output);
                codeLength += this.oad.encode(output);
            } else {
                throw new IllegalArgumentException("oad || dar is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.toByteArray());
    }

    @Override
    public String toString() {
        if (this.oad != null && this.dar != null) {
            return "sequence: {" + "oad: " + this.oad + ", dar: " + this.dar + "}";
        } else {
            return "oad || result is null";
        }
    }
}



